package com.zhongshengnetwork.rightbe;

import android.app.Activity;
//import android.app.ActivityManager;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
//import android.support.multidex.MultiDex;
//import android.support.multidex.MultiDexApplication;
import android.preference.PreferenceManager;
import android.util.Log;

import androidx.multidex.MultiDex;

import com.gui.ninegrideview.MyImageLoader;
import com.pj.core.BaseApplication;
import com.pj.core.http.HttpImage;
import com.pj.core.res.AppConfig;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.zhongshengnetwork.rightbe.Adv.activity.SplashActivity;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.Constant.WeiBoConstant;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.AppUtils;
import com.zhongshengnetwork.rightbe.common.RCCommandUtils;
import com.zhongshengnetwork.rightbe.common.Region.DBCopyUtil;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.AddressbookdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.AtMsgdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.ChatdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.GroupUserdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.GroupdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.LangPublishdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.MessageNotifydbModel;
import com.zhongshengnetwork.rightbe.dbmodel.NotifydbModel;
import com.zhongshengnetwork.rightbe.dbservice.AtMsgdbService;
import com.zhongshengnetwork.rightbe.dbservice.ChatdbService;
import com.zhongshengnetwork.rightbe.dbservice.GroupUserdbService;
import com.zhongshengnetwork.rightbe.dbservice.GroupdbService;
import com.zhongshengnetwork.rightbe.dbservice.MessageNotifydbService;
import com.zhongshengnetwork.rightbe.dbservice.NotifydbService;
import com.zhongshengnetwork.rightbe.game.model.PKMessage;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;

import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.x;
import org.xutils.DbManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
//import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoader;
//import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
//import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.qiniu.android.common.Zone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.MessageDefine;
import com.zhongshengnetwork.rightbe.dbmodel.LogindbModel;
import com.zhongshengnetwork.rightbe.dbmodel.UserInfodbModel;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.dbservice.UserInfodbService;
import com.zhongshengnetwork.rightbe.gsonmodel.GoodsTypeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.MsgUserInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserSignModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.PublicTypeActivity;
import com.zhongshengnetwork.rightbe.lang.viewmodel.LetterViewModel;
import com.zhongshengnetwork.rightbe.my.activity.SettingsActivity;


import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

////import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import cn.jiguang.api.JCoreInterface;
import cn.jpush.android.api.JPushInterface;
import io.rong.imlib.AnnotationNotFoundException;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.InformationNotificationMessage;
import io.rong.push.RongPushClient;

/**
 * Created by GordonLjx on 2016/9/14.
 */
public class CustomApplication  extends BaseApplication {

    //字体相关
    //private List<Activity> activityList;
    private float fontScale;

    public static String centerName = "积分";
    public static String topicTitle;
    public static int meBuyCount = 0;
    private Vibrator vibrator;//震动
    public static boolean isSign = false;
    private static long lasttime = 0;
    public static final String WX_APPID = "wxf630a6ae2120808c";
    public static final String WX_Secrect = "9fb22c301f8370c3b57b4473880a4852";
    //public static DisplayImageOptions options;
    public static RequestQueue requestQueue = null;//volley
    // 超时时间
    public static final int TIMEOUT = 1000 * 60;
    //public static OkHttpClient okHttpClient;//OKHttp
    public static LogindbModel loginModel = null;
    public static Context mContext;
    public static DbManager.DaoConfig daoConfig;
    public static int unReadMessageCount = 0;//未读消息数量
    public static List<GoodsTypeModel>goodsTypeList;
    public static String mCity = null;
    public static double longtitude;
    public static double latitude;
    public static boolean isGetLocation = false;
    public static boolean isHasOne = true;
    public static boolean isAutoLogin = false;
    public static boolean isWatchingImg = false;
    public static boolean isGettingData = false; //用来控制图片轮播
    //高德地图相关
    //声明AMapLocationClient类对象
    public static AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    //声明AMapLocationClientOption对象
    public static AMapLocationClientOption mLocationOption = null;
    //聊天相关
    public static boolean isChatting = false;//当前是否正在聊天
    public static Conversation.ConversationType mConversationType;//聊天类型
    public static String targetId;//聊天对象

    //七牛云存储相关
    public static UploadManager uploadManager = null;
    public static Tencent mTencent;// 新建Tencent实例用于调用分享方法
    //微信支付
    public static IWXAPI mWxApi;

    public static CustomApplication customApplication = null;
    private static Handler handler = new Handler();

    public static long getTipTime = 0;//获取提示时间间隔
    public final static long getTipGasTime = 600;//0.6s

    public static WbShareHandler shareHandler = null;//微博分享
    public final static String WbAppKey = "801656242";
    public static String WbShareText = "";
    public static String WbShareTitle = "";
    public static String WbShareActionUrl = "";
    public static int WbShareType = 0;//0-评论 1-微句 2-专题 3-签到 4-微纸条内容
    public static String WbShareSourceId = "";//分享内容Id
    public static boolean wbHasImage = false;
    public static Bitmap wbShareBitmap = null; //分享的图片


    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private int timeCount = 0;
    private static int delay = 5000;  //5s
    private static int period = 5000;  //5s

    /**
     * 解决oppoR9 TimeoutExceptions
     */
    public void fix() {
        try {
            Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

            Method method = clazz.getSuperclass().getDeclaredMethod("stop");
            method.setAccessible(true);

            Field field = clazz.getDeclaredField("INSTANCE");
            field.setAccessible(true);

            method.invoke(field.get(null));

        }
        catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
        fix();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        customApplication = this;
        mContext = getApplicationContext();

        fontScale = getFontScale();


        //初始化主题：2020年2月19日
        int appTheme = SPManageUtils.getInstance(mContext).getSPInt(AppThemeUtils.AppThemeKey, AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme);
        AppThemeUtils.getInstance().setAppTheme(appTheme);

        //高德地图
        //initLocation();

        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (CommonUtils.isLogin() == false && flag == true){
            //用户未同意隐私协议，不初始化SDK
        }else {
            initSDK();
        }

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                /*
                if(activityList == null){
                    activityList = new ArrayList<>();
                }
                */
                // 禁止字体大小随系统设置变化
                Resources resources = activity.getResources();
                if (resources != null && resources.getConfiguration().fontScale != fontScale) {
                    android.content.res.Configuration configuration = resources.getConfiguration();
                    configuration.fontScale = fontScale;
                    //设置大小
                    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
                }
                //activityList.add(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                /*
                if(activityList != null){
                    activityList.remove(activity);
                }
                */
            }
        });
        //注册前后台监控
        this.registerActivityLifecycleCallbacks(new MyLifecycleHandler());
        // 程序崩溃时触发线程  以下用来捕获程序崩溃异常
        Thread.setDefaultUncaughtExceptionHandler(threadhandler);
        //Log.e("TAG","高德地图签名："+sHA1(mContext));
    }


    public void initSDK(){

        try {
            InputStream is = getAssets().open("app.config");
            if (is != null){
                AppConfig.resetConfigByStream(is);
                is.close();
            }
        } catch (Exception e) {

        }

        // xUtils初始化
        try{
            x.Ext.init(this);
            // 设置是否输出debug
            //x.Ext.setDebug(true);
            daoConfig = new DbManager.DaoConfig()
                    .setDbName("igo_db")//创建数据库的名称igo_db
                    .setDbVersion(5)//数据库版本号
                    .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                        @Override
                        public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                            // TODO: ...
                            // db.addColumn(...);
                            //db.dropTable(...);
                            // ...
                            Log.e("oldVersion",oldVersion+"");
                            Log.e("newVersion", newVersion+"");
                            /*
                            if (oldVersion == 1 && newVersion == 2){
                                try {
                                    db.addColumn(LogindbModel.class, "weiJuId");
                                }catch (Exception e){
                                    LangPublishActivity.uploadError("数据库增加字段异常："+e.getMessage());
                                }
                            }else if (oldVersion == 2 && newVersion == 3){
                                try {
                                    db.addColumn(LogindbModel.class, "mobile");
                                    db.addColumn(LogindbModel.class, "need");
                                }catch (Exception e){
                                    LangPublishActivity.uploadError("数据库增加字段异常："+e.getMessage());
                                }
                            }
                            */
                            if (oldVersion != newVersion){
                                try {
                                    if (oldVersion == 1){
                                        db.addColumn(LangPublishdbModel.class, "filter");
                                        db.addColumn(NotifydbModel.class, "msgtype");
                                        db.addColumn(LogindbModel.class, "mobile");
                                        db.addColumn(LogindbModel.class, "need");
                                        db.addColumn(LogindbModel.class, "weiJuId");
                                    }else if (oldVersion == 2){
                                        db.addColumn(NotifydbModel.class, "msgtype");
                                        db.addColumn(LogindbModel.class, "mobile");
                                        db.addColumn(LogindbModel.class, "need");
                                        db.addColumn(LangPublishdbModel.class, "filter");
                                    }else if (oldVersion == 3){
                                        db.addColumn(NotifydbModel.class, "msgtype");
                                        db.addColumn(LangPublishdbModel.class, "filter");
                                    }else if (oldVersion == 4){
                                        db.addColumn(LangPublishdbModel.class, "filter");
                                    }

                                }catch (Exception e){
                                    LangPublishActivity.uploadError("数据库增加字段异常："+e.getMessage());
                                }
                            }


                        }
                    });//数据库更新操作
            File destDir = new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES)+"mydb");
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            daoConfig.setDbDir(destDir);
        }catch (Exception e){

        }

        loginModel = LogindbService.getLogindbModel();
        if (loginModel == null){
            loginModel = new LogindbModel();
            loginModel.setUid("1");//默认用户id
            loginModel.setThumbheader("");
            loginModel.setBackground("");
            loginModel.setHeader("");
            loginModel.setNickname("");
            loginModel.setSex("0");
            loginModel.setLocation("");
            loginModel.setSignature("");
            loginModel.setRctoken("");
            loginModel.setToken("");
            loginModel.setWeiJuId("");
        }

        //不必为每一次HTTP请求都创建一个RequestQueue对象，推荐在application中初始化
        requestQueue = Volley.newRequestQueue(this);

        initImageLoader(mContext);

        Tencent.setIsPermissionGranted(true);//必须调研这个再调用其他接口
        mTencent = Tencent.createInstance("1105905402",mContext,"com.zhongshengnetwork.rightbe.fileprovider");

        //注册到微信
        mWxApi = WXAPIFactory.createWXAPI(mContext, WX_APPID, true);
        mWxApi.registerApp(WX_APPID);
//        final IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
//        //将该App注册到微信
//        msgApi.registerApp(WX_APPID);

        //初始化七牛云
        initQiniu();
        //极光推送初始化
        JPushInterface.setLbsEnable(mContext, false);//禁止启动定位
        JPushInterface.setDebugMode(false); 	// 设置开启日志,发布时请关闭日志
        JCoreInterface.setWakeEnable(mContext,false);
        JPushInterface.init(mContext);     		// 初始化 JPush

        init();
    }

    private Thread.UncaughtExceptionHandler threadhandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            StringBuffer err = new StringBuffer();
            StackTraceElement[] stack = e.getStackTrace();
            for (int i = 0; i < stack.length; i++) {
                err.append("\tat ");
                err.append(stack[i].toString());
                err.append("\n");
            }
            //Log.e("TAG", err.toString());
            boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
            if (CommonUtils.isLogin() == false && flag == true){//未同意隐私协议
                return;
            }
            LangPublishActivity.uploadError("捕获到了全局异常栈信息："+CommonUtils.formatString(err.toString()));
            LangPublishActivity.uploadError("捕获到了全局异常："+CommonUtils.formatString(e.getMessage()));
            //restartApp(); //发生崩溃异常时,重启应用
        }
    };
    private void restartApp() {
        /*
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                customApplication.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        //退出程序
        AlarmManager mgr = (AlarmManager)customApplication.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                restartIntent); // 1秒钟后重启应用

        //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
        android.os.Process.killProcess(android.os.Process.myPid());
        */


        //Intent intent = new Intent(this, MainActivity.class);
        Intent intent = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
        //android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);

    }

    //初始化
    public void init(){
        getTipTime = 0;
        //不必为每一次HTTP请求都创建一个RequestQueue对象，推荐在application中初始化
        //requestQueue = Volley.newRequestQueue(this);
        goodsTypeList = new ArrayList<GoodsTypeModel>();
        //测试读取手机联系人
        //RCCommandUtils.testReadAllContacts();
        //startLocation();
        //System.out.print("高德地图签名："+sHA1(mContext)+"\n");
        //initRCloud();//2018年11月10日屏蔽
        new Thread() {
            @Override
            public void run() {
                super.run();
                //拷贝地区数据库
                DBCopyUtil.copyDataBaseFromAssets(mContext, "region.db");

            }
        }.start();

    }


    public void initRCloud(){
        /**
         * OnCreate 会被多个进程重入，这段保护代码，确保只有你需要使用 RongIMClient 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */

        //2018年11月10日屏蔽
        /*
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {
            RongIMClient.init(this);//融云SDK初始化
            registMessageType();//注册融云自定义消息类型
        }
        //设置监听器来监听接收到的消息
        RongIMClient.setOnReceiveMessageListener(new MyReceiveMessageListener());
        //融云连接监听
        RongIMClient.setConnectionStatusListener(new MyConnectionStatusListener());
        */
    }

    //连接融云
    public void initRongIMClient(){
        //2018年11月10日屏蔽
        /*
         Log.e("TAG","连接融云");
        //先判断是否已经过期
        if (!CommonUtils.isEmpty(loginModel.getToken())){
            if(loginModel.getToken().contains("a-")==false){
                connect(loginModel.getRctoken());
            }
            //System.out.print("登陆刷新过期\n");
            final Map<String,String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey,loginModel.getToken());
            HttpsUtils.refreshDo(map, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        loginModel.setExpires((String) commonModel.getCount());
                        LogindbService.saveOrUpdateLogindbMode(loginModel);
                    }else {
                        showTip(commonModel,MyActivityManager.getInstance().getCurrentActivity());
                    }
                }

                @Override
                public void onError(String msg) {
                    connect(loginModel.getRctoken());
                }
            });
        }
        */
    }


    //七牛云初始化
    public void initQiniu(){
        if (uploadManager == null){
            Configuration config = new Configuration.Builder()
                    .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                    .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                    .connectTimeout(100) // 链接超时。默认10秒
                    .responseTimeout(100) // 服务器响应超时。默认60秒
                    .recorder(null)  // recorder分片上传时，已上传片记录器。默认null
                    .recorder(null, null)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                    //.zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                    .build();
            // 重用uploadManager。一般地，只需要创建一个uploadManager对象
            uploadManager = new UploadManager(config);
        }

    }


    public void initLocation(){
        System.out.print("高德签名："+sHA1(mContext)+"\n");
        if (mLocationClient != null){
            return;//防止重复初始化
        }
        //高德地图相关
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置单次定位
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否强制刷新WIFI，默认为true，强制刷新。
        mLocationOption.setWifiActiveScan(false);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //AMapLocationClientOption.setProtocol是静态方法。
//AMapLocationClientOption.AMapLocationProtocol提供良种枚举：
//HTTP代表使用http请求，HTTPS代表使用https请求。
//单个定位客户端生命周期内（调用AMapLocationClient.onDestroy()方法结束生命周期）设置一次即可。
        //AMapLocationClientOption.setProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
    }

    public static void startLocation(){
        //启动定位
        if (mLocationClient == null){
            return;
        }
        mLocationClient.startLocation();
        System.out.print("开始定位" +
                "\n");
    }


    public static void getLocation(){
        //启动定位
        if (mLocationClient == null){
            return;
        }
        mLocationClient.startLocation();
        isGetLocation = true;
        System.out.print("开始定位" +
                "\n");
    }

    //可以通过类implement方式实现AMapLocationListener接口，也可以通过创造接口类对象的方法实现
//以下为后者的举例：
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            System.out.print("定位结束" +
                    "\n");
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    //停止定位
                    if (mLocationClient != null){
                        mLocationClient.stopLocation();
                    }
                    Intent mIntent;
                    if (isGetLocation == true){
                        isGetLocation = false;
                        mIntent = new Intent(BroadcastDefine.Get_City);
                    }else {
                        mIntent = new Intent(BroadcastDefine.Get_Location);
                    }
                    mCity = amapLocation.getCity();
                    longtitude = amapLocation.getLongitude();
                    latitude = amapLocation.getLatitude();
                    mIntent.putExtra(APIKey.nationKey, CommonUtils.formatString(amapLocation.getCountry()));
                    mIntent.putExtra(APIKey.provinceKey,CommonUtils.formatString(amapLocation.getProvince()));
                    mIntent.putExtra(APIKey.cityKey,CommonUtils.formatString(amapLocation.getCity()));
                    mIntent.putExtra(APIKey.locationKey,CommonUtils.formatString(amapLocation.getAoiName()));
                    mIntent.putExtra(APIKey.longtitudeKey,amapLocation.getLongitude());
                    mIntent.putExtra(APIKey.latitudeKey,amapLocation.getLatitude());
                    //发送广播
                    sendBroadcast(mIntent);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                    Log.e("AmapError","location Error, ErrCode:"
//                            + amapLocation.getErrorCode() + ", errInfo:"
//                            + amapLocation.getErrorInfo());
                    ToastUtil.show(mContext,"当前无法定位，请检查系统定位功能是否允许");
                    Intent mIntent;
                    if (isGetLocation == true){
                        isGetLocation = false;
                        mIntent = new Intent(BroadcastDefine.Get_City);
                    }else {
                        mIntent = new Intent(BroadcastDefine.Get_Location);
                    }
                    mCity = "";
                    mIntent.putExtra(APIKey.nationKey, "");
                    mIntent.putExtra(APIKey.provinceKey,"");
                    mIntent.putExtra(APIKey.cityKey,"");
                    mIntent.putExtra(APIKey.locationKey,"");
                    //发送广播
                    sendBroadcast(mIntent);
                }
            }

        }
    };

    /**
     * 注册融云自定义消息
     */
    private void registMessageType() {
        try {
            RongIMClient.registerMessageType(PKMessage.class);
        } catch (AnnotationNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static String getCurProcessName(Context context) {
        /*
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        */
        return null;
    }

    /**
     * 建立与融云服务器的连接
     *
     * @param token
     */
    private void connect(String token) {
        Log.e("TAG","融云token:"+token);
         Log.e("TAG","建立与融云服务器的连接1:"+getApplicationInfo().packageName);
        Log.e("TAG","建立与融云服务器的连接2:"+getCurProcessName(getApplicationContext()));
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {
            Log.e("TAG","IMKit SDK融云调用第二步,建立与服务器的连接");
            /**
             * IMKit SDK调用第二步,建立与服务器的连接
             */
            RongIMClient.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误，在线上环境下主要是因为 Token 已经过期，你需要向 App Server 重新请求一个新的 Token
                 */
                @Override
                public void onTokenIncorrect() {
                    Log.e("LoginActivity", "--onTokenIncorrect");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token
                 */
                @Override
                public void onSuccess(String userid) {
                    Log.e("LoginActivity", "--onSuccess---" + userid);
                    //监听融云链接
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Log.e("LoginActivity", "--onError" + errorCode);
                }
            });
        }
    }

    //融云连接状态监听
    private class MyConnectionStatusListener implements RongIMClient.ConnectionStatusListener{
        @Override
        public void onChanged(ConnectionStatus connectionStatus) {
            Log.e("TAG","融云连接状态："+connectionStatus);
            if (connectionStatus == ConnectionStatus.NETWORK_UNAVAILABLE){//网络不可用

            }else if (connectionStatus == ConnectionStatus.CONNECTED){//连接成功
                Intent mIntent = new Intent(BroadcastDefine.RC_ConnectState);
                mIntent.putExtra(APIKey.stateKey,0);
                //发送广播
                sendBroadcast(mIntent);
            }else if (connectionStatus == ConnectionStatus.CONNECTING){//连接中
                Intent mIntent = new Intent(BroadcastDefine.RC_ConnectState);
                mIntent.putExtra(APIKey.stateKey,1);
                //发送广播
                sendBroadcast(mIntent);
            }else if (connectionStatus == ConnectionStatus.DISCONNECTED){//断开连接
                Intent mIntent = new Intent(BroadcastDefine.RC_ConnectState);
                mIntent.putExtra(APIKey.stateKey,2);
                //发送广播
                sendBroadcast(mIntent);
            }else if (connectionStatus == ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT){//用户账户在其他设备登录，本机会被踢掉线。
                System.out.print("用户账户在其他设备登录，本机会被踢掉线。\n");
                Intent mIntent = new Intent(BroadcastDefine.Logout_Success_Action);
                mIntent.putExtra(APIKey.typeKey,1);
                //发送广播
                sendBroadcast(mIntent);
            }else if (connectionStatus == ConnectionStatus.TOKEN_INCORRECT){//Token 不正确

            }else if (connectionStatus == ConnectionStatus.SERVER_INVALID){//服务器异常或无法连接。

            }
        }
    }

    //接收消息监听器的实现，所有接收到的消息、通知、状态都经由此处设置的监听器处理。包括私聊消息、讨论组消息、群组消息、聊天室消息以及各种状态
    private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {
        /**
         * 收到消息的处理。
         * @param message 收到的消息实体。
         * @param left 剩余未拉取消息数目。
         * @return
         */
        @Override
        public boolean onReceived(Message message, int left) {
            //开发者根据自己需求自行处理
            if (message.getObjectName().equals(MessageDefine.pk_msg)){
                if (System.currentTimeMillis()-message.getSentTime() < 60000){
                    PKMessage pkMessage = new PKMessage(message.getContent().encode());
                    Log.e("TAG","PK消息："+pkMessage.getContent()+"\n");
                    Intent mIntent = new Intent(BroadcastDefine.PKMsg);
                    mIntent.putExtra(APIKey.contentKey,pkMessage.getContent());
                    //发送广播
                    sendBroadcast(mIntent);
                }

            }else if (message.getObjectName().equals(MessageDefine.cmd_msg)){
                Log.e("TAG","通知消息："+message.getObjectName()+"\n");
                //通知
                try{
                    String dataString = new String(message.getContent().encode(),"utf-8");
                    JSONObject jsonObject = CommonUtils.stringToJson(dataString);
                    String msgname = jsonObject.getString("name");
                    String data = jsonObject.getString("data");
                    if (msgname.equals(Constant.MessageType.Life_Result)) {//生活圈审核结果
                        RCCommandUtils.dealWithLifeResult(data,mContext,message.getSentTime());
                    }else if (msgname.equals(Constant.MessageType.LifeLike_Result)) {//生活圈关注
                        RCCommandUtils.dealWithCare(data,mContext,message.getSentTime());
                    }else if (msgname.equals(Constant.MessageType.LifeDZ_Result)) {//生活圈笔芯信息
                        RCCommandUtils.dealWithLife(data,Integer.valueOf(Constant.MessageType.LifeDZ_Result),mContext,message.getSentTime());
                    }else if (msgname.equals(Constant.MessageType.LifeC_Result)) {//生活圈评论信息
                        RCCommandUtils.dealWithLife(data,Integer.valueOf(Constant.MessageType.LifeC_Result),mContext,message.getSentTime());
                    }else if (msgname.equals(Constant.MessageType.LifeCR_Result)) {//生活圈评论回复
                        RCCommandUtils.dealWithLife(data,Integer.valueOf(Constant.MessageType.LifeCR_Result),mContext,message.getSentTime());
                    }else if (msgname.equals(Constant.MessageType.LifeCL_Result)) {//生活圈评论笔芯
                        RCCommandUtils.dealWithLife(data,Integer.valueOf(Constant.MessageType.LifeCL_Result),mContext,message.getSentTime());
                    }else if (msgname.equals(Constant.MessageType.LangPrize_Result)) {//生活圈获奖
                        RCCommandUtils.dealWithLife(data,Integer.valueOf(Constant.MessageType.LangPrize_Result),mContext,message.getSentTime());
                    }
                }catch (Exception e){

                }
            }
            return true;
        }

    }

    //系统提示
    private void systemNotify(){
        long nowtime = System.currentTimeMillis();
        if (nowtime - lasttime > 3000){
            lasttime = nowtime;
            MessageNotifydbModel messageNotifydbModel = MessageNotifydbService.getModel(CustomApplication.loginModel.getUid());
            if (messageNotifydbModel.getAll() == 1){
                if (messageNotifydbModel.getMove() == 1){
                            /*
                             * 想设置震动大小可以通过改变pattern来设定，如果开启时间太短，震动效果可能感觉不到
                            * */
                    vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                    long [] pattern = {100,400,100,400};   // 停止 开启 停止 开启
                    vibrator.vibrate(pattern,-1);           //重复两次上面的pattern 如果只想震动一次，index设为-1
                }
                if (messageNotifydbModel.getSound() == 1){
                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                    r.play();
                }
            }
        }else {
            lasttime = nowtime;
        }

    }

    private void dealWithUserGroupInfo(Message message){

    }

    //处理小灰条消息
    private void dealWithInfoMessage(Message message){
        InformationNotificationMessage informationNotificationMessage = (InformationNotificationMessage)message.getContent();
        if (informationNotificationMessage.getExtra() == null || informationNotificationMessage.getExtra().length() == 0){
            return;
        }
        String groupid = RCCommandUtils.xiaoHuiTiaoInfo(informationNotificationMessage.getExtra());
        if (groupid != null && isChatting == true){
            Intent mIntent = new Intent(BroadcastDefine.Group_Member_Update);
            mIntent.putExtra(APIKey.groupidKey,groupid);
            //发送广播
            sendBroadcast(mIntent);
        }
    }

    /**
     * 获取未读消息数量
     */
    private void dealWithNewMessage(){
        RongIMClient.getInstance().getTotalUnreadCount(new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    public void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        MyImageLoader.getInstance(context);
        HttpImage.getInstance(context);

        /*
        .memoryCacheSize(2 * 1024 * 1024) //缓存到内存的最大数据
                .memoryCacheSize(50 * 1024 * 1024) //设置内存缓存的大小
                .diskCacheFileCount(200)
                */
    }

    /**
     * 功能：获取当前APP的高德地图的sha1签名
     * @param
     * @return
     */
    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    //公共提醒处理
    public static void showTip(final CommonModel model, final Activity activity){

        if (activity != null){


            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    /**
                     *要执行的操作
                     */
                    if (model.getCode().equals(Constant.UserReturnCode.CODE_10011)){//登录过期
                        if (!CommonUtils.isEmpty(model.getMsg())){
                            ToastUtil.show(activity,model.getMsg());
                        }
                        if (activity instanceof MainActivity){
                            Intent mIntent = new Intent(BroadcastDefine.Logout_Success_Action);
                            //发送广播
                            activity.sendBroadcast(mIntent);
                        }else {
                            /*
                            CustomApplication.isSign = false;
                            CustomApplication.loginModel.setToken(null);
                            LogindbService.deleteLoginModel();
                            Intent intent = new Intent(mContext, MainActivity.class);
                            intent.putExtra(AppUtils.KEY_HOME_ACTION, AppUtils.ACTION_LOGOUT);
                            mContext.startActivity(intent);
                            */
                            activity.finish();
                            Intent mIntent = new Intent(BroadcastDefine.Logout_Success_Action);
                            //发送广播
                            activity.sendBroadcast(mIntent);
                        }

                    }else{
                        if (!CommonUtils.isEmpty(model.getMsg())){
                            ToastUtil.show(activity,model.getMsg());
                        }
                    }
                }
            }, 5);//3秒后执行Runnable中的run方法
        }
    }

    public static void showFailTip(Activity activity){
        ToastUtil.show(activity,"网络似乎断开连接了");
    }


    /**********************************前后台监控************************************/
    public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {

        private int count = 0;

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (count == 0) { //后台切换到前台
                //Log.e("MyLifecycleHandler", ">>>>>>>>>>>>>>>>>>>App切到前台");
                boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
                if (flag == true && CommonUtils.isLogin() == false ){
                    //用户未同意隐私政策
                }else {
                    startTimer();
                }
            }
            count++;
        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {
            count--;
            if (count == 0) { //前台切换到后台
                //Log.e("danxx", ">>>>>>>>>>>>>>>>>>>App切到后台");
                stopTimer();
                boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
                if (flag == true && CommonUtils.isLogin() == false ){//未同意隐私政策
                    killAppProcess();
                }
            }
        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }
    }

    public void killAppProcess()
    {
        //注意：不能先杀掉主进程，否则逻辑代码无法继续执行，需先杀掉相关进程最后杀掉主进程
        ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> mList = mActivityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : mList)
        {
            if (runningAppProcessInfo.pid != android.os.Process.myPid())
            {
                android.os.Process.killProcess(runningAppProcessInfo.pid);
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    private void startTimer(){

        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {

                    if (AppUtils.getInstance().getAppStatus() != AppUtils.STATUS_NORMAL){
                        return;
                    }

                    boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
                    if (flag == true && CommonUtils.isLogin() == false ){//用户未同意隐私政策
                        return;
                    }

                    boolean unReadOfSXMSG = SPManageUtils.getInstance(mContext).getSPBoolean(LetterConstant.UnReadOfSXMSGKey, false);
                    String inChat = SPManageUtils.getInstance(mContext).getSPString(LetterConstant.InChatKey, "");
                    boolean inMessage = SPManageUtils.getInstance(mContext).getSPBoolean(LetterConstant.InMessageKey, false);
                    if (inChat.length() > 0 || inMessage == true){
                        //不计算阅读时长
                        if (timeCount % 60 == 0){
                            timeCount += 5;
                        }
                    }else {
                        //定时事件到了
                        timeCount += 5;
                    }
                    Log.e("TAG", "时间到了"+timeCount);


                    if (unReadOfSXMSG == true || inChat.length() > 0 || inMessage == true){
                        //获取私信
                        Log.e("TAG", "获取私信:"+unReadOfSXMSG+":"+inChat+":"+inMessage);
                        LetterViewModel.getSX();
                    }


                    boolean blackAsyn = SPManageUtils.getInstance(mContext).getSPBoolean(LetterConstant.SXBlackAsyncKey, false);
                    if (blackAsyn == false){

                        int page = SPManageUtils.getInstance(mContext).getSPInt(LetterConstant.SXBlackPageKey,0);
                        if (page == 0){
                            LetterViewModel.getSXState();
                        }
                        //获取黑名单
                        LetterViewModel.getBlack();

                    }

                    Log.e("TAG","定时时间到了:"+timeCount);

                    if (CommonUtils.isLogin() == true){
                        if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), false) == true){
                            Log.e("TAG", "有未读消息");
                            MainActivity.getUnReadMsg();
                        }
                    }
                    dealWithReadTime();

                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            mTimer.schedule(mTimerTask, delay, period);
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            timeCount = 0;
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        timeCount = 0;
    }


    private void dealWithReadTime(){
        if (CommonUtils.isLogin() == true){
            int lastRecordTime = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.LastRecordTimeKey+loginModel.getUid(),0);
            if (lastRecordTime == 0){
                //第一次记录
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.ReadTimeKey+loginModel.getUid(),1);
                SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.LastRecordTimeKey+loginModel.getUid(),(int)(System.currentTimeMillis()/1000));
            }else {
                //判断是否是是今天
                if (CommonUtils.isToday(lastRecordTime)){
                    //今天
                    if (timeCount > 0 && timeCount % 60 == 0){
                        int time = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.ReadTimeKey+loginModel.getUid(),0);
                        time += 1;
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.ReadTimeKey+loginModel.getUid(),time);
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.LastRecordTimeKey+loginModel.getUid(),(int)(System.currentTimeMillis()/1000));

                        //发送通知更新时间
                        Intent mIntent = new Intent(BroadcastDefine.ReadTime_Update_Action);
                        CustomApplication.mContext.sendBroadcast(mIntent);

                        if (time % 5 == 0){
                            //5分钟上次一次服务器
                            new Thread(){
                                @Override
                                public void run() {
                                    super.run();
                                    final HashMap<String, String> map = new HashMap<String, String>();
                                    map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                                    map.put(APIKey.countKey,SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.ReadTimeKey+loginModel.getUid(),0)+"");
                                    String url = "miniapp/"+"langappid"+"/readcount.do";
                                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                                        @Override
                                        public void onSuccess(String data) {
                                            Log.e("TAG","阅读上传结果："+data);
                                            CommonModel commonModel = GsonTools.getCommonModel(data);
                                            if (commonModel.getFlag().equals("1")){
                                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserReadData+CustomApplication.loginModel.getUid(),data);
                                                UserSignModel userSignModel = GsonTools.getUserSignModel(data);
                                                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), userSignModel.isUnRead());
                                                if (userSignModel.getReadCount() >= 20){//评价提示
                                                    int commentCount = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.CommentAppKey,0);
                                                    if (commentCount == 0){
                                                        if (userSignModel.isOpenComment() == true){
                                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.CommentAppKey, 1);
                                                        }
                                                    }
                                                }
                                                if (!CommonUtils.isEmpty(commonModel.getMsg())){
                                                    //发送通知显示通知
                                                    Intent mIntent = new Intent(BroadcastDefine.Read_Notify_Action);
                                                    mIntent.putExtra("readNotify",commonModel.getMsg());
                                                    CustomApplication.mContext.sendBroadcast(mIntent);
                                                }

                                            }
                                        }

                                        @Override
                                        public void onError(String msg) {

                                        }
                                    });
                                }
                            }.start();
                        }
                    }
                }else {
                    //非今天，清零
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.ReadTimeKey+loginModel.getUid(),1);
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.LastRecordTimeKey+loginModel.getUid(),(int)(System.currentTimeMillis()/1000));
                    //发送通知更新时间
                    Intent mIntent = new Intent(BroadcastDefine.ReadTime_Update_Action);
                    CustomApplication.mContext.sendBroadcast(mIntent);
                }
            }

        }
    }

    /**********************************前后台监控************************************/


    //以下字体相关
    //获取设置字体大小值
    public static float getFontScale() {
        float fontScale = 1.0f;
        if (customApplication != null) {
            String font = SPManageUtils.getInstance(customApplication).getSPString("fontScale","1.0");
            fontScale = Float.valueOf(font);
        }
        return fontScale;
    }

    //保存字体大小
    public static boolean saveFontScale(float fontScale){
        if (customApplication != null) {
            customApplication.fontScale = fontScale;
            DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            String f = decimalFormat.format(fontScale);
            SPManageUtils.getInstance(customApplication).putSPString("fontScale", f);
            return true;
        }
        return false;
    }

    //调用该方法即可
    /*
    public static void setAppFontSize(float fontScale,Activity context) {
        if (customApplication != null) {
            List<Activity> activityList = customApplication.activityList;
            if (activityList != null) {
                for (Activity activity : activityList) {
                    //当前页面设置重启会闪黑屏
                    if (activity instanceof FontSizeActivity) {
                        continue;
                    }
                    Resources resources = activity.getResources();
                    if (resources != null) {
                        android.content.res.Configuration configuration = resources.getConfiguration();
                        configuration.fontScale = fontScale;
                        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
                        activity.recreate();
                        if (fontScale != customApplication.fontScale) {
                            customApplication.fontScale = fontScale;
                            //保存设置后的字体大小
                            customApplication.preferences.edit().putFloat("fontScale", fontScale);
                        }
                    }
                }
            }
        }
    }
    */

}
